<template>
  <view class="login-container">
    <view class="login-header">
      <image class="logo" src="/static/logo.png" mode="aspectFit"></image>
      <text class="title">Hot Tomato</text>
    </view>

    <view class="login-content">
      <!-- 登录方式切换 -->
      <view class="login-tabs">
        <view 
          v-for="(tab, index) in tabs" 
          :key="index"
          class="tab-item"
          :class="{ active: currentType === tab.type }"
          @click="switchTab(tab.type)"
        >
          {{ tab.name }}
        </view>
      </view>

      <!-- 微信登录 -->
      <view v-if="currentType === 'wechat'" class="login-form">
        <button class="wechat-btn" @click="handleWechatLogin">
          <text>微信一键登录</text>
        </button>
      </view>

      <!-- 手机验证码登录 -->
      <!-- <view v-if="currentTab === 1" class="login-form">
        <input 
            type="number" 
            v-model="phone" 
            placeholder="请输入手机号"
            maxlength="11"
          />
        <view class="input-group">
          <input 
            type="number" 
            v-model="code" 
            placeholder="请输入手机验证码"
            maxlength="6"
          />
          <button 
            class="send-code-btn" 
            :disabled="countdown > 0"
            @click="sendVerificationCode"
          >
            {{ countdown > 0 ? `${countdown}s` : '发送验证码' }}
          </button>
        </view>
        <button class="submit-btn" @click="handlePhoneLogin">登录</button>
      </view> -->
	  
	  <!-- 账号登录 -->
      <view v-else-if="currentType === 'email'" class="login-form">
        <!-- <input 
          type="text" 
          v-model="username" 
          placeholder="请输入账号"
        /> -->
        <input 
          type="email" 
          v-model="email" 
          placeholder="请输入邮箱"
        />
        <input 
          type="password" 
          v-model="password" 
          placeholder="请输入密码"
        />
        <!-- <view class="input-wrapper  login-form">
          <input class="custom-input" type="text" v-model="captchaCodeText"  placeholder="请输入图片验证码" maxlength="4" ></input>
          <image class="input-icon" :src="captchaCodeImage" mode="widthFix" @click="refreshCaptcha" />
        </view> -->
        <!--注册按钮右边显示，点击注册按钮跳转到注册页面-->
        <view class="register-btn-wrapper">
          <text class="forget-password" @click="handleForgetPassword">忘记密码</text>
          <text class="register-btn" @click="handleRegister">注册新用户</text>
        </view>
        <button class="submit-btn" @click="handleEmailLogin">登录</button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()

// #ifdef MP-WEIXIN
const tabs = [{ type:'wechat',name: '微信登录'},{ type:'email',name:"邮箱登录" }];
const currentType = ref('wechat')
// #endif

// #ifdef H5
const tabs = [{ type:'email',name:"邮箱登录" }]
const currentType = ref('email')
// #endif

// 手机验证码登录相关
const phone = ref('')
const code = ref('')
const countdown = ref(0)

//用户名密码登录相关
const username = ref('')
const password = ref('')
const captchaId = ref('')
const captchaCodeText = ref('')
const captchaCodeImage = ref('')

//邮箱登录相关
const email = ref('')


onMounted(async() => {
  // TODO: 判断用户是否已登录
  refreshCaptcha();
  
})

const refreshCaptcha = async() => {
  // TODO: 刷新验证码
  try{
  	  let res = await userStore.getImgCode();
	  const { captchaId:chaId , data } = res;
	  captchaId.value = chaId;
	  captchaCodeImage.value = data;
  }catch(error){
  	  console.log('userStore.getImgCode error',error);
  }
}	

// 切换登录方式
const switchTab = (type) => {
  currentType.value = type
}

// 发送验证码
const sendVerificationCode = async () => {
  if (!phone.value) {
    uni.showToast({
      title: '请输入手机号',
      icon: 'none'
    })
    return
  }
  
  // TODO: 调用发送验证码接口
  try{
    let res = await userStore.sendSmsCode(phone.value)
    console.log('userStore.sendSmsCode res',res)
  }catch(error){
    console.log('userStore.sendSmsCode error',error)
    uni.showToast({
      title: '发送验证码失败:' + error.message,
      icon: 'none'
    })
    return;
  }

  countdown.value = 60
  const timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
}

// 微信登录
const handleWechatLogin = async () => {
  try {
    const { code } = await uni.login({
      provider: 'weixin'
    })
    const userInfo = await uni.getUserInfo({
      provider:'weixin',
    })

    console.log('wechat userInfo',userInfo);

    const {encryptedData,iv} = userInfo;
  
    // TODO: 调用微信登录接口
    await userStore.loginByWechat(code,encryptedData,iv)
    
    uni.showToast({
      title: '登录成功',
      icon: 'success'
    })
    uni.switchTab({
      url: '/pages/my/my'
    })

  } catch (error) {
    uni.showToast({
      title: '登录失败' + error.message,
      icon: 'none'
    })
  }
}

// 手机验证码登录
const handlePhoneLogin = async () => {
  if (!phone.value || !code.value) {
    uni.showToast({
      title: '请填写完整信息',
      icon: 'none'
    })
    return
  }
  
  try {
    // TODO: 调用手机验证码登录接口
    await userStore.loginByPhone(phone.value, code.value)
    uni.showToast({
      title: '登录成功',
      icon: 'success'
    })
    uni.navigateBack()
  } catch (error) {
    uni.showToast({
      title: '',
      icon: 'none'
    })
  }
}

//账号密码登录
const handleUsernameLogin = async () => {
  console.log(`username: ${username.value}, password: ${password.value}, captchaId: ${captchaId.value}, captchaCodeText: ${captchaCodeText.value}`);
  if (!username.value || !password.value || !captchaId.value || !captchaCodeText.value) {
    uni.showToast({
      title: '请填写完整信息',
      icon: 'none'
    })
    return
  }
  try{
	  // TODO: 调用账号密码登录接口
    await userStore.loginByAccount(username.value, password.value,captchaId.value,captchaCodeText.value)
    uni.showToast({
      title: '登录成功',
      icon: 'success'
    })
    // 登录成功后跳转到我的页面
    uni.switchTab({
      url: '/pages/my/my'
    })
  } catch (error) {
	console.log('userStore.loginByAccount error',error)
    uni.showToast({
      title: '登录失败:' + error.message,
      icon: 'none'
    })
  }
}


//邮箱登录
const handleEmailLogin = async () => {
  console.log(`email: ${email.value}, password: ${password.value}`);
  if (!email.value || !password.value) {
    uni.showToast({
      title: '请填写完整信息',
      icon: 'none'
    })
    return
  }
  try{
    // TODO: 调用邮箱登录接口
    await userStore.loginByEmail({email:email.value, password:password.value})
    uni.showToast({
      title: '登录成功',
      icon: 'success'
    })
    uni.switchTab({
      url: '/pages/my/my'
    })
  }catch(error){
    console.log('userStore.loginByEmail error',error)
    uni.showToast({
      title: '登录失败:' + error.message,
      icon: 'none'
    })
  }

}

//注册新用户
const handleRegister = async () => {
  uni.navigateTo({
    url: '/pages/register/index'
  })
}

//忘记密码
const handleForgetPassword = async () => {
  uni.navigateTo({
    url: '/pages/forgetPwd/index'
  })
}

</script>

<style lang="scss">
.login-container {
  padding: 40rpx;
  padding-top: var(--uni-safe-area-inset-top, 80px);
  min-height: 100vh;
  background-color: #f8f8f8;
}

.login-header {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 60rpx;
  
  .logo {
    width: 120rpx;
    height: 120rpx;
    margin-bottom: 20rpx;
  }
  
  .title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
  }
}

.login-content {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 40rpx;
}

.login-tabs {
  display: flex;
  margin-bottom: 40rpx;
  border-bottom: 2rpx solid #eee;
  
  .tab-item {
    flex: 1;
    text-align: center;
    padding: 20rpx 0;
    font-size: 28rpx;
    color: #666;
    
    &.active {
      color: #007AFF;
      position: relative;
      
      &::after {
        content: '';
        position: absolute;
        bottom: -2rpx;
        left: 50%;
        transform: translateX(-50%);
        width: 40rpx;
        height: 4rpx;
        background-color: #007AFF;
        border-radius: 2rpx;
      }
    }
  }
}

.login-form {
  .input-group {
    display: flex;
    margin-bottom: 30rpx;
    
    input {
      flex: 1;
      height: 80rpx;
      padding: 0 20rpx;
      border: 2rpx solid #eee;
      border-radius: 8rpx;
      font-size: 28rpx;
    }
    
    .send-code-btn {
      width: 200rpx;
      height: 80rpx;
      line-height:80rpx;
      margin-left: 20rpx;
      background-color: #007AFF;
      color: #fff;
      font-size: 24rpx;
      border-radius: 8rpx;
      
      &:disabled {
        background-color: #ccc;
      }
    }
  }
  
  input {
    width: 100%;
    height: 80rpx;
    padding: 0 20rpx;
    margin-bottom: 30rpx;
    border: 2rpx solid #eee;
    border-radius: 8rpx;
    font-size: 28rpx;
  }
  
  .wechat-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 80rpx;
    background-color: #07C160;
    color: #fff;
    font-size: 28rpx;
    border-radius: 8rpx;
    
    image {
      width: 40rpx;
      height: 40rpx;
      margin-right: 10rpx;
    }
  }
  
  .submit-btn {
    width: 100%;
    height: 80rpx;
    background-color: #007AFF;
    color: #fff;
    font-size: 28rpx;
    border-radius: 8rpx;
  }
  
  .input-wrapper {
    position: relative;
    display: inline-block; /* 或者使用 flex，根据需要 */
    width: 100%; /* 根据需要调整宽度 */
	.custom-input {
	}
	 
	.input-icon {
	  position: absolute;
	  right: 10px; /* 图标距离输入框右侧的距离 */
	  top: 40%;
	  transform: translateY(-60%); /* 垂直居中 */
	  width: 200rpx; /* 根据需要调整图标大小 */
	  height: 50rpx; 
    z-index: 100;
	}
  }
   
  .register-btn-wrapper {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    margin-top: 20rpx;
    margin-bottom: 20rpx;
    cursor: pointer;
    .register-btn {
      color:#007AFF;
      font-size: 28rpx;
    }
    .forget-password {
      color:#007AFF;
      font-size: 28rpx;
    }
  }

}
</style> 